package IO;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import ItemUser.MoiveRate;
import ItemUser.UserRate;

public class DataHandler {
	DataResources resources = null;
	HashMap<Long,ArrayList<UserRate>> item_to_user = new HashMap<>();
	HashMap<Long,ArrayList<MoiveRate>> user_to_item = new HashMap<>();
	BufferedReader reader;
	
	public DataHandler(String path){
		resources = new DataResources(path);
		if(resources.load()){
		}else{
			System.out.println("读取文件失败");
			System.exit(0);
		}
	}
	public void mapByUserID() throws IOException{
		reader = new BufferedReader(new FileReader(resources.getFile()));
		ArrayList<MoiveRate> arraylist = null;
		String tempString = null;
		String tempUserId = null;
        while ((tempString = reader.readLine()) != null) {
            //
            String[] strArray = tempString.split("::");
            
            if(tempUserId == null ){
            	//开头
            	tempUserId = strArray[0];
            	arraylist = new ArrayList<>();
            	
            }else if(tempUserId.equals(strArray[0])){
            	//同一个userid
            	
            }else {
            	//不同的userid
            	user_to_item.put(Long.valueOf(tempUserId).longValue(),
            			arraylist);
            	tempUserId = strArray[0];
            	arraylist = new ArrayList<>();
           
            }
            arraylist.add(new MoiveRate(Long.valueOf(strArray[1]).longValue(),
            		Double.valueOf(strArray[2]).floatValue()));
        }
        reader.close();
        System.out.println("user_to_item加载完成");
	}
	
	public void mapByMovieID() throws IOException{
		reader = new BufferedReader(new FileReader(resources.getFile()));
		ArrayList<UserRate> arraylist = null;
		String tempString = null;

		while ((tempString = reader.readLine()) != null) {
			String[] strArray = tempString.split("::");
			
			arraylist = item_to_user.get(Long.
					valueOf(strArray[1]).
					longValue());
			if(arraylist == null){
				arraylist = new ArrayList<>();
				item_to_user.put(Long.valueOf(strArray[1]).longValue(),
						arraylist);
			}
			arraylist.add(new UserRate(Long.valueOf(strArray[0]).longValue(),
					Double.valueOf(strArray[2]).floatValue()));
			arraylist = null;
        }
		reader.close();
		System.out.println("item_to_user加载完成");
	}

	public HashMap<Long,ArrayList<MoiveRate>> getUserToItem(){
		return this.user_to_item;
	}
	public HashMap<Long,ArrayList<UserRate>> getItemToUser(){
		return this.item_to_user;
	}
	
	
}
